<script type="text/javascript" >
$(document).ready(function() {
    $('#form1').bootstrapValidator({
        message: 'This value is not valid',
        excluded : [':disabled'],
        feedbackIcons: {
            //valid: 'glyphicon glyphicon-ok',
            //invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            IP: {
                message: 'The IP is not valid',
                validators: {
                    notEmpty: {
                        message: '请选择主机'
                    },
                }
            },
            PORT: {
                message: 'The PORT is not valid',
                validators: {
                    notEmpty: {
                        message: '端口不能为空'
                    },
                }
            },

        }
    });
    $('#form2').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            password: {
                message: 'The password is not valid',
                validators: {
                    notEmpty: {
                        message: '密码不能为空'
                    },
                }
            },

        }
    });
    $('#form3').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            user: {
                message: 'The user is not valid',
                validators: {
                    notEmpty: {
                        message: '用户名不能为空'
                    },
                }
            },
            host: {
                message: 'The host is not valid',
                validators: {
                    notEmpty: {
                        message: '授权主机不能为空'
                    },
                }
            },
            dbname: {
                message: 'The dbname is not valid',
                validators: {
                    notEmpty: {
                        message: '授权数据库不能为空'
                    },
                }
            },
            db_type: {
                message: 'The type is not valid',
                validators: {
                    notEmpty: {
                        message: '权限类别不能为空'
                    },
                }
            }
        }
    });
    $('#form4').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            database: {
                message: 'The database is not valid',
                validators: {
                    notEmpty: {
                        message: '数据库不能为空'
                    },
                }
            },

        }
    });
});
function confirmAct(){
    //var action=action;
    $('#form1').data('bootstrapValidator').validate();//手动对表单进行校检
    if (!$('#form1').data('bootstrapValidator').isValid()) {//判断校检是否通过
        // alert("验证不通过");
        return;
    }else {
        showMask();
        return user_select();
    }
}
function confirmAdd() {
    $('#form3').data('bootstrapValidator').validate();//手动对表单进行校检
    if (!$('#form3').data('bootstrapValidator').isValid()) {//判断校检是否通过
        // alert("验证不通过");
        return;
    }else {
        return user_add();
    }
}
function confirmMod() {
    $('#form2').data('bootstrapValidator').validate();//手动对表单进行校检
    if (!$('#form2').data('bootstrapValidator').isValid()) {//判断校检是否通过
        // alert("验证不通过");
        return;
    }else {
        return mod_password();
    }
}
function  confirmDat() {
    $('#form4').data('bootstrapValidator').validate();//手动对表单进行校检
    if (!$('#form4').data('bootstrapValidator').isValid()) {//判断校检是否通过
        // alert("验证不通过");
        return;
    }else {
        return add_database();
    }
}
function user_select(){
    var formdata=new FormData($("#form1")[0]);
    var ip=$('#IP option:selected').val();
    $('#text_ip').html(ip);
    var port=$('#PORT option:selected').val();
    document.cookie="PORT="+port+";path=/";
    $.ajax({
        url: '/mysql/user/',
        type: 'POST',
        data: formdata,
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        success:function (callback) {
            console.log(callback);
            hideMask();
            user_list=JSON.parse(callback);
            $('.dynamicCreate').remove();
            $('#dynamicCreate').show();
            var tr=$('#dynamicCreate');
            $.each(user_list,function (index,item) {
                var cloneTr=tr.clone();
                cloneTr.children("td").each(function (inner_index) {
                    switch(inner_index){
                        case(0):
                            $(this).html(item[0]);
                            break;
                        case(1):
                            $(this).html(item[1]);
                            break;
                        case(2):
                            var html_ele='<button  class="btn btn-primary btn-sm" onclick="confirmDel(this)">删除</button>' +
                                '<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal">修改密码</button>' +
                                '<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal3">查询</button>';
                            $(this).html(html_ele);
                            break;
                    }
                });
                cloneTr.insertAfter(tr);
                cloneTr.attr('id',index);
                cloneTr.attr('class','dynamicCreate');

            });
            $('#dynamicCreate').hide();
            $('.table').show();
            if(user_list.length==0){
                $('#mysql_add').html('');
                alert("mysql连接异常！");
            }else{
                var button_ele='<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal2">新增授权</button>' +
                    '<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal4">新增数据库</button>' +
                    '<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal5">数据库查询</button>';
                $('#mysql_add').html(button_ele);

            }

        },
        error: function () {
            hideMask();
            $('.dynamicCreate').remove();
            $('#mysql_add').html('');
            alert('主机不可连接！');
        }

    });
}

function confirmDel(ele){
    if(confirm("你确定要删除该用户下所有授权吗？")){
        return del_user(ele);
    }
}

function del_user(ele) {
    var html_ele=ele;
    var ip=$('#text_ip').text(); //获取mysql的IP
    var user=$(html_ele).parent().prev().prev().text(); //获取mysql的用户
    var host=$(html_ele).parent().prev().text(); //获取mysql用户的授权主机
    $.ajax({
        url: '/mysql/delete/',
        type: 'POST',
        data: {ip:ip,user:user,host:host},
        success: function (callback) {
            if(callback==0){
                user_select();
            }else{
                alert('删除出现异常！');
            }
        }
    })

}

function user_add() {
    var formdata=new FormData($("#form3")[0]);
    var ip=$('#text_ip').text();
    formdata.append('ip',ip);
    $.ajax({
        url: '/mysql/add/',
        type: 'POST',
        data: formdata,
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        success: function (callback) {
            if(callback==0){
                $('#password1').val('');
                $('#myModal2').modal('hide');
                user_select();
            }else{
                alert('添加失败！');
            }
        }
    })

}


function add_database() {
    var formdata=new FormData($("#form4")[0]);
    var ip=$('#text_ip').text();
    formdata.append('ip',ip);
    $.ajax({
        url: '/mysql/add/database/',
        type: 'POST',
        data: formdata,
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        success: function (callback) {
            if(callback==0){
                $('#database').val('');
            }else{
                alert('添加失败！');
            }
            $('#myModal4').modal('hide');
        }
    })
}

function mod_password(){
    var formdata=new FormData($("#form2")[0]);
    var ip=$('#text_ip').text();
    formdata.append('ip',ip);
    console.log();
    $.ajax({
        url: '/mysql/modified/',
        type: 'POST',
        data: formdata,
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        success: function (callback) {
            console.log(callback);
            if (callback==0){
                $('#password').val('');
                alert('密码更新成功！');
                $('#myModal').modal('hide');
            }else{
                alert('密码更新失败！');
            }


        }
    })
}


$(function() {
    $('#myModal').on('show.bs.modal',
    function(event) {
        var button=$(event.relatedTarget);
        var user=$(button).parent().prev().prev().text(); //获取mysql的用户
        var host=$(button).parent().prev().text(); //获取mysql用户的授权主机
        var modal = $(this); //获得模态框本身
        modal.find('#user').val(user);
        modal.find('#host').val(host);
    })
});
$(function () {
    $('#myModal3').on('show.bs.modal',
        function(event) {
            var button=$(event.relatedTarget);
            var ip=$('#text_ip').text();
            var user=$(button).parent().prev().prev().text(); //获取mysql的用户
            var host=$(button).parent().prev().text(); //获取mysql用户的授权主机
            $.ajax({
                url: '/mysql/user/priv/',
                type: 'POST',
                data: {ip:ip,user:user,host:host},
                success:function (callback) {
                    console.log(callback);
                    user_list=JSON.parse(callback);
                    $('.dynamicCreate1').remove();
                    $('#dynamicCreate1').show();
                    var tr=$('#dynamicCreate1');
                    $.each(user_list,function (index,item) {
                        var cloneTr=tr.clone();
                        cloneTr.children("td").each(function (inner_index) {
                            switch(inner_index){
                                case(0):
                                    $(this).html(item[0]);
                                    break;
                                case(1):
                                    $(this).html(item[1]);
                                    break;
                                case(2):
                                    $(this).html(item[2]);
                                    break;
                                case(3):
                                    var html_ele='<button  class="btn btn-primary btn-sm" onclick="confirmDelPriv(this)">删除</button>';
                                    $(this).html(html_ele);
                                    break;
                            }
                        });
                        cloneTr.insertAfter(tr);
                        cloneTr.attr('id',index);
                        cloneTr.attr('class','dynamicCreate1');

                    });
                    $('#dynamicCreate1').hide();
                    $('.table').show();

                },
                error: function () {
                    $('.dynamicCreate1').remove();
                    alert('主机不可连接！');
                }

            });
        })

});

$(function () {
    $('#myModal5').on('show.bs.modal',
        function(event) {
            var button=$(event.relatedTarget);
            var ip=$('#text_ip').text();
            $.ajax({
                url: '/mysql/select/database/',
                type: 'POST',
                data: {ip:ip},
                success:function (callback) {
                    console.log(callback);
                    db_list=JSON.parse(callback);
                    $('.dynamicCreate2').remove();
                    $('#dynamicCreate2').show();
                    var tr=$('#dynamicCreate2');
                    $.each(db_list,function (index,item) {
                        var cloneTr=tr.clone();
                        cloneTr.children("td").each(function (inner_index) {
                            switch(inner_index){
                                case(0):
                                    $(this).html(db_list.length-parseInt(index));
                                    break;
                                case(1):
                                    $(this).html(item[0]);
                                    break;
                            }
                        });
                        cloneTr.insertAfter(tr);
                        cloneTr.attr('class','dynamicCreate2');

                    });
                    $('#dynamicCreate2').hide();
                    $('.table').show();

                },
                error: function () {
                    $('.dynamicCreate2').remove();
                    alert('主机不可连接！');
                }

            });
        })

});

function confirmDelPriv(ele) {
    if(confirm("你确定删除该授权吗？")){
        return del_priv(ele);
    }
}

function del_priv(ele){
    var ip=$('#text_ip').text();
    var user=$(ele).parent().prev().prev().prev().text();
    var host=$(ele).parent().prev().prev().text();
    var dbname=$(ele).parent().prev().text();
    $.ajax({
        url: '/mysql/del/priv/',
        type: 'POST',
        data: {ip:ip,user:user,host:host,dbname:dbname},
        success:function (callback) {
            console.log(callback);
            if(callback==0){
                $(ele).parent().parent().hide();
            }else{
                alert('删除授权失败');
            }
        }
    })
}

function select_port(ele){
    var ip=ele.value;
    showMask();
    $.ajax({
        url: '/mysql/select/port/',
        type: 'POST',
        data: {ip:ip},
        async: true,
        success: function (callback) {
            hideMask();
            var port_list=JSON.parse(callback);
            console.log(port_list);
            var html='';
            console.log(port_list.length);
            $.each(port_list,function(index,value){
                html+="<option value='"+value+"'>"+value+"</option>";
            });

            $('#PORT').html(html);
            $('.dynamicCreate').remove();
            $('#mysql_add').html('');
        },
        error: function () {
            $('.dynamicCreate').remove();
            $('#mysql_add').html('');
        }
    })
}


function change_port(ele) {
    var port=$('#PORT option:selected').val();
    document.cookie="PORT="+port+";path=/";
    $('.dynamicCreate').remove();
    $('#mysql_add').html('');
}

function showMask(){
    $("#mask").css("height",$(document).height());
    $("#mask").css("width",$(document).width());
    $("#mask").show();
}
//隐藏遮罩层
function hideMask(){

    $("#mask").hide();
}


function check_first(ele) {
    if(ele.checked){
        $('#password1').removeAttr('readonly');
    }else{
        $('#password1').attr('readonly','readonly');
    }
}




function generateMixed(n) {
     var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a',
'b','c','d','e','f','g','h','i','j','k','l','n','m','o','p','q','r','s','t','u','v','w','x','y','z','$','#','@','%'];
     var res = "";
     for(var i = 0; i < n ; i ++) {
         var id = Math.ceil(Math.random()*65);
         res += chars[id];
     }
     console.log(res);
     $('#password1').val(res);
}
$(function () {
    $('.selectpicker').selectpicker({
        'selectedText': 'cat'
    });
})
</script>